package com.example.lib_common.mvi

import android.graphics.Color
import android.graphics.drawable.AnimationDrawable
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.Window
import android.view.WindowManager
import android.widget.ImageView
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.transition.Visibility
import androidx.viewbinding.ViewBinding
import com.example.lib_common.R
import com.example.lib_common.mvi.custom.LoadDialog
import kotlinx.coroutines.launch


abstract class BaseActivity<V : ViewBinding,VM : BaseViewModel<*,*>> : AppCompatActivity() {
    protected lateinit var vm : VM
    abstract fun createVM():VM
    abstract fun createViewBinding():ViewBinding
    protected val inflater : LayoutInflater by lazy { LayoutInflater.from(this) }
    protected lateinit var v : V
    val tag = "log"
    private lateinit var dialog: LoadDialog

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        vm=createVM()
        v= createViewBinding() as V
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            val window: Window = window
            window.clearFlags(
                WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
                        or WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION
            )
            window.getDecorView().setSystemUiVisibility(
                (View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                        or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                        or View.SYSTEM_UI_FLAG_LAYOUT_STABLE)
            )
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
            window.setStatusBarColor(Color.TRANSPARENT)
            window.setNavigationBarColor(Color.TRANSPARENT)
        }
        window.requestFeature(Window.FEATURE_NO_TITLE)
        setContentView(v.root)
        initStateFlow()
    }

    private fun initStateFlow() {
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED){
                vm.mutableContainer.requestStateFlow.collect{
                    if (it.request){
                        showDialog()
                    }else if (it.complete){
                        hideDialog()
                    }else if(it.error){
                        showEmptyView()
                    }
                }
            }
        }
    }
    fun showDialog(){
//        dialog = LoadDialog(this)
//        dialog.show()
    }
    fun hideDialog(){
//        dialog = LoadDialog(this)
//        dialog.dismiss()
    }
    fun showEmptyView(){
        println("showEmptyView")
    }
    fun log(msg : String){
        Log.e(tag,msg)
    }

}